<?php
class Menu extends Action {
	private $menuitem_types = array ('url' => '自定义','page' => '页面','cate' => '栏目' );
	/*
	 * (non-PHPdoc) @see Action::execute()
	 */
	public function execute($params) {
		check_login ( ADMIN_LOGIN_PAGE );
		$data = array ();
		$op = rqst ( 'op' );
		$menu_id = irqst ( 'mid', 0 );
		
		$mM = new WebMenuModel ();
		$menus = $mM->retrieve ();
		
		if (empty ( $op ) && empty ( $menu_id )) { // 取默认的主导航菜单
			$menu_id = $mM->get ( 'menu_id', array ('menu_default' => 1 ) );
		}
		$menu = array ();
		$menuitems = array ();
		if (! empty ( $menu_id ) && empty ( $op )) {
			$menu = $mM->read ( $menu_id );
			$miM = new WebMenuItemModel ();
			$menuitems = $miM->getSubItems ( $menu ['menu_name'], 0 );
			$data ['menu'] = $menu;
		} else {
			$op = 'add';
		}
		if ($op == 'add') {
			$data ['menu'] = sess_del ( 'menu_info' );
		}
		$suc = irqst ( 'suc', 0 );
		$data ['alert_cls'] = $suc ? 'alert-success' : 'alert-error';
		$data ['page_tip_info'] = sess_del ( 'page_tip_info' );
		$data ['items'] = $menuitems;
		$data ['menus'] = $menus ? $menus : array ();
		$data ['navi'] = 'menu';
		$data ['op'] = $op;
		$data ['menu_id'] = $menu_id;
		// 分类
		$cM = new WebPageCategory ();
		$data ['treeNodes'] = json_encode ( $cM->getTreeNodes ( 0 ) );
		$pM = new WebPageModel ();
		$pages = $pM->where ( array ('status' => 'published' ) )->sortDesc ( 'publish_time' )->limit ( 10 )->retrieve ( 'page_id,title' );
		$data ['npages'] = $pages ? $pages : array ();
		bind ( 'output_menu_items', array ($this,'output_menu_items' ), 10, 2 );
		return new SmartyView ( $data, 'vfs/Menu' );
	}
	//输出菜单项处理器
	public function output_menu_items($html, $items) {
		static $miM = false;
		if (! $miM) {
			$miM = new WebMenuItemModel ();
		}
		if (! $items) {
			return $html;
		}
		foreach ( $items as $item ) {
			$item ['type_name'] = $this->menuitem_types [$item ['type']];
			
			$view = new SmartyView ( array ('adding' => false,'items' => array ($item ) ), 'vfs/AddMenuItem' );
			$itemText = $view->render ( $this, 'core' );
			$html .= '<li id="menu-item-' . $item ['menuitem_id'] . '">' . $itemText;
			$subitems = $miM->getSubItems ( $item ['menu_name'], $item ['menuitem_id'] );
			if ($subitems && count ( $subitems ) > 0) {
				$html .= '<ol>';
				$html .= $this->output_menu_items ( '', $subitems );
				$html .= '</ol>';
			}
			$html .= '</li>';
		}
		return $html;
	}
}